package config

import (
	"github.com/spf13/cast"
	"sync"
)

type KeyValue interface {
	Get(key string) (any, bool)
	GetString(key string) string
	GetInt32(key string) int32
	GetInt64(key string) int64
	Set(key string, value interface{})
	SetString(key, value string)
	SetInt32(key string, value int32)
	SetInt64(key string, value int64)
}

type ConfigMap struct {
	mu   sync.RWMutex // 读写锁（读多写少时性能更好）
	Data map[string]any
}

func (s *ConfigMap) isExist() {
	if s.Data == nil {
		s.Data = make(map[string]any)
	}
}
func (s *ConfigMap) Get(key string) (any, bool) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	val, ok := s.Data[key]
	return val, ok
}

func (s *ConfigMap) GetString(key string) string {
	s.mu.RLock()
	defer s.mu.RUnlock()
	val, ok := s.Data[key]
	if !ok {
		return ""
	}
	return cast.ToString(val)
}

func (s *ConfigMap) GetInt32(key string) int32 {
	s.mu.RLock()
	defer s.mu.RUnlock()
	val, ok := s.Data[key]
	if !ok {
		return 0
	}
	return cast.ToInt32(val)
}

func (s *ConfigMap) GetInt64(key string) int64 {
	s.mu.RLock()
	defer s.mu.RUnlock()
	val, ok := s.Data[key]
	if !ok {
		return 0
	}
	return cast.ToInt64(val)
}

func (s *ConfigMap) Set(key string, value any) {
	s.isExist()
	s.mu.Lock()
	defer s.mu.Unlock()
	s.Data[key] = value
}

func (s *ConfigMap) SetString(key, value string) {
	s.isExist()
	s.mu.Lock()
	defer s.mu.Unlock()
	s.Data[key] = value
}

func (s *ConfigMap) SetInt32(key string, value int32) {
	s.isExist()
	s.mu.Lock()
	defer s.mu.Unlock()
	s.Data[key] = value
}
func (s *ConfigMap) SetInt64(key string, value int64) {
	s.isExist()
	s.mu.Lock()
	defer s.mu.Unlock()
	s.Data[key] = value
}

type GinConfig struct {
	RunMode      string `json:"run_mode" yaml:"run_mode" mapstructure:"run_mode"`
	HttpPort     int    `json:"http_port" yaml:"http_port" mapstructure:"http_port"`
	ReadTimeout  int    `json:"read_timeout" yaml:"read_timeout" mapstructure:"read_timeout"`
	WriteTimeout int    `json:"write_timeout" yaml:"write_timeout" mapstructure:"write_timeout"`
}

type GrpcConfig struct {
	GrpcPort   int    `json:"grpc_port" yaml:"grpc_port" mapstructure:"grpc_port"`
	CrtPath    string `json:"crt_path" yaml:"crt_path" mapstructure:"crt_path"`
	KeyPath    string `json:"key_path" yaml:"key_path" mapstructure:"key_path"`
	CaPath     string `json:"ca_path" yaml:"ca_path" mapstructure:"ca_path"`
	CnHostName string `json:"cn_host_name" yaml:"cn_host_name" mapstructure:"cn_host_name"`
}

type GinLog struct {
	LogFilePath string `json:"log_file_path" yaml:"log_file_path" mapstructure:"log_file_path"`
	LogFileExt  string `json:"log_file_ext" yaml:"log_file_ext" mapstructure:"log_file_ext"`
}
